package com.qdu;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;

import java.io.IOException;

public class HBaseAdmin {
    public static void main(String[] args) {
        Configuration conf = HBaseConfiguration.create();
        conf.set("hbase.zookeeper.quorum", "niit-master");

        conf.setInt("hbase.rpc.timeout", 20000);
        conf.setInt("hbase.client.operation.timeout", 20000);
        conf.setInt("hbase.client.scanner.timeout.period", 20000);

        try (
                Connection connection = ConnectionFactory.createConnection(conf);
                // 创建用于管理的Admin实例
                Admin admin = connection.getAdmin()
        ) {
            // 这是一种新版本的API
            // 获取表的引用
            TableName mytable = TableName.valueOf("mytable");
            // 判断表是否存在
            // 如果不存在，那么
            if(!admin.tableExists(mytable)){
                //    创建TableDescriptorBuilder
                TableDescriptorBuilder tableDescriptorBuilder = TableDescriptorBuilder
                                                                    .newBuilder(mytable);
                //    创建ColumnFamilyDescriptorBuilder
                ColumnFamilyDescriptorBuilder columnFamilyDescriptorBuilder = ColumnFamilyDescriptorBuilder
                                                                    .newBuilder(Bytes.toBytes("cf1"));
                //    将列族对象添加到表描述符
                tableDescriptorBuilder.setColumnFamily(columnFamilyDescriptorBuilder.build());
                //    通过admin调用
                admin.createTable(tableDescriptorBuilder.build());
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
